#include <stdio.h>
#include "StdThread.h"
#include <unistd.h>
#include <pthread.h>
Mutex*m;
Cond *Print;
int flag = 0; //flag = 0 A打印 flag = 1 B打印
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* func1(void *arg)
{
    while(1)
    {   
        //抢锁
        MutexLock(m);
        while(flag != 0)  //不符合打印条件，循环等待条件变量
        //等待打印A的信号,锁会被放开
        CondWait(Print,m);

        sleep(1);
        printf("A\n");
        flag = 1; //需要B打印
        //唤醒线程B
        CondBroadcast(Print);
        MutexUnlock(m);
    }
}

void * func2(void* arg)
{
    while(1)
    {   
        MutexLock(m);
        while(flag != 1)
        //等待打印B的信号
        CondWait(Print,m); //阻塞线程 锁放开 
                           //尝试重新上锁，继续执行
        sleep(1);
        printf("B\n");
        flag = 2;
        //唤醒线程A
        CondBroadcast(Print);
        MutexUnlock(m);
    }
}

 void* func3(void *arg)
{
    while(1)
    {   
        //抢锁
        MutexLock(m);
        while(flag != 2)  //不符合打印条件，循环等待条件变量
        //等待打印A的信号,锁会被放开
        CondWait(Print,m);

        sleep(1);
        printf("C\n");
        flag = 0; //需要B打印
        //唤醒线程B
        CondBroadcast(Print);
        MutexUnlock(m);
    }
}   


int main()
{
    
    m = MutexInit();
    Print = CondInit();
    Thread * t1 = ThreadInit(func1,NULL);
    Thread * t2 = ThreadInit(func2,NULL);
    Thread * t3 = ThreadInit(func3,NULL);
    
    //等到线程启动了再发信号
    
    ThreadJoin(t1);
    ThreadJoin(t2);
    ThreadJoin(t3);
    ClearThread(t1);
    ClearThread(t2);
    ClearThread(t3);

    ClearMutex(m);
}